package org.chipu.shared.util.file;

import java.io.RandomAccessFile;

public class ReverseFileReader {
	private RandomAccessFile randomfile;
	/** Current position in the file */
	private long position;

	public ReverseFileReader(String filename) throws Exception {
		randomfile = new RandomAccessFile(filename, "r");
		position = randomfile.length();
		randomfile.seek(position);
		// Move our pointer to the first valid position at the end of the file.
		String thisLine = randomfile.readLine();
		while(thisLine == null) {
			position--;
			randomfile.seek(position);
			thisLine = randomfile.readLine();
			randomfile.seek(position);
		}
	}

	/** Read one line from the current position towards the beginning */
	public String readLine() throws Exception {
		int thisCode;
		char thisChar;
		String finalLine = "";

		// If our position is less than zero already, we are at the beginning with nothing to
		// return.
		if (position < 0)
			return null;

		for(;;) {
			if (position < 0)
				// we've reached the beginning of the file
				break;
			randomfile.seek(position);

			// Read the data at this position
			thisCode = randomfile.readByte();
			thisChar = (char) thisCode;

			// If this is a line break or carriage return, stop looking
			if (thisCode == 13 || thisCode == 10) {
				// See if the previous character is also a line break character.
				// this accounts for crlf combinations
				randomfile.seek(position - 1);
				int nextCode = randomfile.readByte();
				if ((thisCode == 10 && nextCode == 13) || (thisCode == 13 && nextCode == 10))
					// If we found another line break character, ignore it
					position--;
				// Move the pointer for the next readline
				position--;
				break;
			}
			// This is a valid character append to the string
			finalLine = thisChar + finalLine;
			// Move to the next char
			position--;
		}
		return finalLine;
	}
}